package controllers.wechatlab;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.edu.bjtu.constant.Constant;
import cn.edu.bjtu.entity.ExecuteResult;
import cn.edu.bjtu.entity.impl.local.tiny.Trans2StdLibSVMForamtTask;
import cn.edu.bjtu.settings.ApplicationConfiguration;
import pojo.ResCode;
import service.wechatlab.DataSetService;
import util.io.WechatUploadRegFilterIterator;

@Controller
@RequestMapping(value="dataset")
public class DataSetController extends WechatBaseController{
	
	String wekaDir = null;
	String w2vTransformedDir = null;
	String wechatRawDataDir = null;
	String libsvmData = null;
	
	@Autowired
	DataSetService dss;
	/**
	 * 
	 */
	public DataSetController() {
		sync();
	}
	private void sync(){
		wekaDir = ApplicationConfiguration.getInstance().getProperty("WEKA_FILE_DIR");
		w2vTransformedDir =  ApplicationConfiguration.getInstance().getProperty("WORD2VEC_TRANSFORMED_DIR");
		wechatRawDataDir = ApplicationConfiguration.getInstance().getProperty("WECHAT_RAW_DATA_DIR");
		libsvmData = ApplicationConfiguration.getInstance().getProperty("LIBSVM_DATA_DIR");
	}
	private String decideWhichDir(HttpServletRequest req){
		sync();
		int type = Integer.parseInt(req.getParameter("type"));
		String dir = null;
		switch(type){
		case 1:
			dir = wekaDir;
			break;
		case 2:
		case 3:
			dir = w2vTransformedDir;
			break;
		case 4:
			dir = wechatRawDataDir;
			break;
		case 5:
			dir = libsvmData;
			break;
		default:
			dir = null;
		}
		return dir;
	}
	
	@RequestMapping(value="/preview.do")
	public void preview(HttpServletRequest req,HttpServletResponse res) throws IOException{
		String dir = decideWhichDir(req);
		String filename = req.getParameter("filename");
		res.setCharacterEncoding("utf-8");
		res.setContentType("text/plain");
		PrintWriter pw = res.getWriter();
		if(!StringUtils.hasText(filename)) pw.print("invalid parameter"); 
		File preview = new File(dir,filename);
		if(preview.exists()){
			try(BufferedReader br = new BufferedReader(new FileReader(preview))){
				String line = "";
				while((line=br.readLine())!=null){
					pw.println(line);	
				}
			}
		}else{
			pw.println("文件不存在,请检查");
		}
	}
	
	@RequestMapping(value="/delete.do")
	@ResponseBody
	public String delete(HttpServletRequest req,HttpServletResponse res) throws IOException{
		String dir = decideWhichDir(req);
		String filename = req.getParameter("filename");
		if(!StringUtils.hasText(filename)) return jsonDump(ParamsError);
		File del = new File(dir,filename);		
		if(del.exists()){
			del.delete();
			return jsonDump(SUCCESS);
		}else{
			return jsonDump(new ResCode(404, "file not exist"));
		}
	}
		
	@RequestMapping(value="/trans.do")
	public ModelAndView trans2std(HttpServletRequest req,HttpServletResponse res) throws IOException{
		Trans2StdLibSVMForamtTask t = new Trans2StdLibSVMForamtTask(req, this::decideWhichDir);
		ExecuteResult<?> er = t.execute(null);
		return renderView("admin/viewTagRendered", null).addObject(Constant.JSP_MAP_RENDER_ATTRIBUTE,er);
	}
	@ResponseBody
	@RequestMapping(value="/export.do")
	public String exportWechatFromDB(HttpServletRequest req){
		String n = req.getParameter("n");
		String filename = req.getParameter("filename");
		String dir = req.getParameter("dir");
		int topn;
		if(n == null || n.equals(""))
			topn = 3;
		else
			topn = Integer.parseInt(n);
		if(!StringUtils.hasText(filename)) 
		    filename = new SimpleDateFormat ("yyyyMMddHHmmss").format(new Date())+".txt"; 
		if(!StringUtils.hasText(dir))
			dir = decideWhichDir(req);
		return dss.modLabel(topn, new File(dir,filename))?jsonDump(SUCCESS):jsonDump(ERROR);
	
	}
	//当文件导入系统的时候就进行过滤.
	@RequestMapping(value="/wechatupload.do")
	@ResponseBody
	public String upload(@RequestParam("file") CommonsMultipartFile files[], HttpServletRequest req,HttpServletResponse res) throws IOException{
	
		if(files != null && files.length>0){
			for(CommonsMultipartFile file :files){
				try{
					//接受文件同时一行一行的写入,然后过滤
					WechatUploadRegFilterIterator li = new WechatUploadRegFilterIterator(file.getInputStream(), "utf-8");
					FileOutputStream fos = new FileOutputStream(new File("E:\\DataSets\\textdata\\out.txt"));
					while(li.hasNext()){
						//过滤
						IOUtils.write(li.next(), fos);
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			//返回成功上传文件数.失败文件数.过滤之后的数据
			return jsonDump(SUCCESS);
		}
		return jsonDump(ParamsError);
	}
	
}
